package com.business.business.support.aspect;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.business.business.common.utils.Dict;
import com.business.business.support.mybatisplus.QueryWrapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 处理查询的通用分页及排序
 *
 * @author
 * @date 2018/12/27 15:44
 */
@Aspect
@Component
public class QueryAspect {
    /**
     * 接口传递参数
     */
    private final String ORDERBY = "orderBy";
    /**
     * 拦截service下所有已list开头、Page结尾的方法
     */
    private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.business.business.web..service.*.list*Page(..))";

    @Pointcut(AOP_POINTCUT_EXPRESSION)
    public void listQuery() {
    }

    @Around("listQuery()")
    public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        //入参必须为Dict否则不支持
        if (args.length == 1 && args[0] instanceof Dict) {
            Dict dict = (Dict) args[0];
            Page<?> queryPage = new Page<>(dict.getInt("page"), dict.getInt("limit"));
            dict.set("__queryPage__", queryPage);
            QueryWrapper<?> queryWrapper = new QueryWrapper<>();
            if (StrUtil.isNotBlank(dict.getStr(ORDERBY))) {
                boolean isAsc = Convert.toStr(dict.get("order"), "").equalsIgnoreCase("asc") ? true : false;
                queryWrapper.orderBy(StrUtil.isNotBlank(dict.getStr("order")), isAsc, dict.getStr("orderBy"));
                if (isAsc) {
                    queryPage.setAsc(dict.getStr("orderBy"));
                } else {
                    queryPage.setDesc(dict.getStr("orderBy"));
                }
            }
            dict.set("__queryWrapper__", queryWrapper);
        }
        return joinPoint.proceed(args);
    }
}
